<template>
  <div class="app-container">
    <el-form ref="noticedemandapprovalRef" :model="formData" :rules="rules" label-width="140px">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="立案号" prop="caseId">
            <el-select
              v-model="formData.caseId"
              placeholder="请选择立案号"
              :disabled="disabled || isFlow"
              clearable
              @change="handleCase">
              <el-option v-for="item in numberList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="案件来源" prop="caseSource">
            <el-select v-model="formData.caseSource" disabled placeholder="请选择案件来源" :style="{ width: '18vw' }">
              <el-option v-for="item in case_source" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="案由" prop="caseCause">
            <el-input v-model="formData.caseCause" disabled placeholder="请输入案由" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="当事人名称" prop="partyName">
            <el-input v-model="formData.partyName" disabled placeholder="请输入当事人名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="邮政编码" prop="postalCode">
            <el-input v-model="formData.postalCode" disabled placeholder="请输入邮政编码" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="统一社会信用代码" prop="unifiedSocialCreditCode">
            <el-input v-model="formData.unifiedSocialCreditCode" disabled placeholder="请输入统一社会信用代码" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input v-model="formData.contactPhone" disabled placeholder="请输入联系电话" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="法定代表人" prop="legalRepresentative">
            <el-input v-model="formData.legalRepresentative" disabled placeholder="请输入法定代表人" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="职务" prop="position">
            <el-input v-model="formData.position" disabled placeholder="请输入职务" />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="地址" :rules="rules.addressObj" prop="addressObj">
            <locationSelect v-model="formData.addressObj" disabled style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="简要案情及销案理由" prop="briefReason">
            <SmartTextInput
              v-model="formData.briefReason"
              type="textarea"
              :rows="4"
              :disabled="disabled"
              placeholder="请输入简要案情及销案理由，输入关键词后按Tab键快速补全"
              :min-length="2"
              :max-suggestions="5"
              contentType="100" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="承办人意见" prop="handlerOpinion">
            <el-input
              v-model="formData.handlerOpinion"
              :disabled="disabled || isFlow"
              type="textarea"
              :rows="3"
              placeholder="请输入承办人意见" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="formData.remark"
              :disabled="disabled"
              type="textarea"
              :rows="3"
              placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance, watch, onBeforeUnmount } from 'vue'
import {
  getCasecancelapproval,
  addCasecancelapproval,
  updateCasecancelapproval,
  getCaseList,
  submitCasecancelapproval,
  reviewCasecancelapproval,
  getContent,
  previewPdf,
} from '@/api/caseWithdrawal/index.js'
import { registrationcaseDetail } from '@/api/filingReview/register'
import { ElMessage } from 'element-plus'
import locationSelect from '@/components/locationSelect/index.vue'
import { useRouter } from 'vue-router'
import { commonRules } from '@/components/DynamicForm/config'
import SmartTextInput from '@/components/SmartTextInput/index.vue'

const { proxy } = getCurrentInstance()
const { case_source } = proxy.useDict('case_source')

// Props
const props = defineProps({
  id: {
    type: [String, Number],
    default: null,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  isFlow: {
    type: Boolean,
    default: false,
  },
})

const router = useRouter()

// Emits
const emit = defineEmits(['handleSubmit'])

// Form data
const formData = ref({
  id: null,
  caseId: null,
  caseNo: null,
  caseSource: null,
  caseCause: null,
  partyName: null,
  postalCode: null,
  streetOfCompanyAddress: null,
  address: null,
  unifiedSocialCreditCode: null,
  legalRepresentative: null,
  position: null,
  briefReason: null,
  handlerOpinion: null,
  remark: null,
})
// 自定义校验器：检查拍摄地点是否完整
const validateLocation = (rule, value, callback) => {
  if (!value || !value.streetOfPhotoLocation || !value.photoLocation) {
    callback(new Error('请选择地点'))
  } else {
    callback()
  }
}
// Form validation rules
const rules = {
  caseNo: [{ required: true, message: '立案号不能为空', trigger: ['blur', 'change'] }],
  caseCause: [{ required: true, message: '案由不能为空', trigger: ['blur', 'change'] }],
  partyName: [{ required: true, message: '当事人名称不能为空', trigger: ['blur', 'change'] }],
  postalCode: [{ required: true, message: '邮政编码不能为空', trigger: ['blur', 'change'] }],
  caseId: [{ required: true, message: '立案号不能为空', trigger: ['blur', 'change'] }],
  caseSource: [{ required: true, message: '案件来源不能为空', trigger: ['blur', 'change'] }],
  legalRepresentative: [{ required: true, message: '法定代表人不能为空', trigger: ['blur', 'change'] }],
  position: [{ required: true, message: '职务不能为空', trigger: ['blur', 'change'] }],
  briefReason: [{ required: true, message: '简要案情及销案理由不能为空', trigger: ['blur', 'change'] }],
  handlerOpinion: [{ required: true, message: '承办人意见不能为空', trigger: ['blur', 'change'] }],
  businessType: [{ required: true, message: '营业执照类型不能为空', trigger: ['blur', 'change'] }],
  unifiedSocialCreditCode: [{ required: true, message: '统一社会信用代码不能为空', trigger: ['blur', 'change'] }],
  contactPhone: [commonRules.phone],
  addressObj: [{ required: true, validator: validateLocation, trigger: ['blur', 'change'] }],
}

// Refs
const noticedemandapprovalRef = ref()

// Methods
const reset = () => {
  formData.value = {
    id: null,
    caseId: null,
    caseSource: null,
    caseNo: null,
    caseCause: null,
    partyName: null,
    postalCode: null,
    streetOfCompanyAddress: null,
    address: null,
    unifiedSocialCreditCode: null,
    legalRepresentative: null,
    position: null,
    briefReason: null,
    handlerOpinion: null,
    remark: null,
  }
  proxy.resetForm('noticedemandapprovalRef')
}

// Get detail data
const getDetail = async id => {
  reset()
  if (id) {
    try {
      const res = await getCasecancelapproval(id)
      if (!res?.data) return
      formData.value = res.data
      formData.value.addressObj = {
        photoLocation: res.data.address,
        streetOfPhotoLocation: res.data.streetOfCompanyAddress,
      }
    } catch (error) {
      console.error('获取详情失败:', error)
    }
  }
}

const handleCase = async val => {
  return new Promise(async (resolve, reject) => {
    if (!val) {
      formData.value.caseNo = ''
      formData.value.caseSource = ''
      formData.value.caseCause = ''
      formData.value.partyName = ''
      formData.value.postalCode = ''
      formData.value.partyId = ''
      formData.value.legalRepresentative = ''
      formData.value.position = ''
      formData.value.briefReason = ''
      formData.value.handlerOpinion = ''
      formData.value.businessType = ''
      formData.value.unifiedSocialCreditCode = ''
      formData.value.contactPhone = ''
      formData.value.addressObj = {
        photoLocation: '',
        streetOfPhotoLocation: '',
      }
      return
    }
    const res = await registrationcaseDetail(val)
    const {
      partyName,
      caseCause,
      caseSource,
      postalCode,
      partyId,
      legalRepresentative,
      position,
      businessType,
      contactPhone,
      unifiedSocialCreditCode,
      streetOfCompanyAddress,
      address,
    } = res.data
    formData.value.caseNo = res.data.caseNo
    formData.value.caseSource = caseSource
    formData.value.caseCause = caseCause
    formData.value.partyName = partyName
    formData.value.postalCode = postalCode
    formData.value.partyId = partyId
    formData.value.legalRepresentative = legalRepresentative
    formData.value.position = position
    formData.value.businessType = businessType
    formData.value.unifiedSocialCreditCode = unifiedSocialCreditCode
    formData.value.contactPhone = contactPhone
    formData.value.addressObj = {
      photoLocation: address,
      streetOfPhotoLocation: streetOfCompanyAddress,
    }
    const res2 = await getContent(val)
    formData.value.briefReason = res2.data.briefReason || ''
    resolve()
  })
}

const handlePreview = () => {
  return new Promise(resolve => {
    submitForm(false, true)
      .then(async params => {
        previewPdf(params)
          .then(res => {
            if (!!res.msg) {
              window.open(res.msg)
              resolve()
            } else {
              ElMessage.warning('预览文件不存在')
              resolve()
            }
          })
          .catch(() => {
            ElMessage.warning('预览文件不存在')
            resolve()
          })
      })
      .catch(() => {
        ElMessage.warning('请先完善表单信息')
        resolve()
      })
  })
}

// Submit form
const caseSituationRef = ref(null)
const submitForm = (isDraft = false, isPreview = false) => {
  return new Promise(async (resolve, reject) => {
    noticedemandapprovalRef.value
      .validate()
      .then(async () => {
        if (isPreview === true) {
          resolve({ ...formData.value })
          return
        }
        formData.value.address = formData.value.addressObj.photoLocation
        formData.value.streetOfCompanyAddress = formData.value.addressObj.streetOfPhotoLocation
        let result
        if (isDraft) {
          // 草稿
          if (formData.value.id) {
            result = await updateCasecancelapproval(formData.value)
          } else {
            result = await addCasecancelapproval(formData.value)
          }
        } else {
          // 提交
          result = await submitCasecancelapproval(formData.value)
        }

        ElMessage.success(isDraft ? '保存草稿成功' : '提交成功')
        emit('handleSubmit', result)
        return result
      })
      .catch(err => {
        reject(err)
      })
  })
}

// 待办页面 提交 / 退回
const handleSubmitReview = async form => {
  await reviewCasecancelapproval({
    ...form,
    id: props.editId || props.id,
  })
  proxy.$modal.msgSuccess('操作成功')
  router.back()
}

// 待办页面获取批注列表
const timer = ref(null)
const getAnnotationList = () => {
  return new Promise((resolve, reject) => {
    timer.value = setInterval(() => {
      if (formData.value.id) {
        clearInterval(timer.value)
        resolve({ ...formData.value })
      } else {
        resolve([])
      }
    }, 500)
  })
}

// Watch props.id change
watch(
  () => props.id,
  newVal => {
    if (newVal) {
      getDetail(newVal)
    } else {
      reset()
    }
    handleCaseList()
  },
  { immediate: true }
)

const numberList = ref([])
async function handleCaseList() {
  const res = await getCaseList()
  numberList.value = res.data.map(item => ({
    label: item.caseNo,
    value: item.id,
  }))
}
onBeforeUnmount(() => {
  if (timer.value) {
    clearInterval(timer.value)
  }
})
// Expose methods
defineExpose({
  submitForm,
  handlePreview,
  reset,
  formData,
  getAnnotationList,
  handleSubmitReview,
  formRef: noticedemandapprovalRef,
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>
